package com.api.zszsj2.ZYT.action;

import cn.hutool.core.date.DateUtil;
import lombok.extern.log4j.Log4j;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j
public class AnnualLeaveExpAction extends BaseBean implements Action {

    public String execute(RequestInfo requestinfo) {
        System.out.println("进入Action requestid=" + requestinfo.getRequestid());
        //数据源
        RecordSet rs = new RecordSet();
        //数据源 //支持回滚
        RecordSetTrans rst = new RecordSetTrans();
        //请求ID
        String requestid = requestinfo.getRequestid();
        //请求紧急程度
        String requestlevel = requestinfo.getRequestlevel();
        //当前操作类型 submit:提交/reject:退回
        String src = requestinfo.getRequestManager().getSrc();
        //流程ID
        String workflowid = requestinfo.getWorkflowid();
        //表单名称 主表
        String tablename = requestinfo.getRequestManager().getBillTableName();
        //	tablename 中的id
        int billid = requestinfo.getRequestManager().getBillid();        //表单数据ID
        //获取当前操作用户对象
        User usr = requestinfo.getRequestManager().getUser();
        //请求标题
        String requestname = requestinfo.getRequestManager().getRequestname();
        //当前用户提交时的签字意见
        String remark = requestinfo.getRequestManager().getRemark();
        //表单ID
        int formid = requestinfo.getRequestManager().getFormid();
        //是否是自定义表单
        int isbill = requestinfo.getRequestManager().getIsbill();
        //取主表数据
        Property[] properties = requestinfo.getMainTableInfo().getProperty();
        // 获取表单主字段信息
        String xgr = ""; //修改人
        String xdnxjssnx = ""; //限定年休假所属年限
        String jqlx = ""; //假期类型

        for (int i = 0; i < properties.length; i++) {
            // 主字段名称
            String name = properties[i].getName();
            // 主字段对应的值
            String value = Util.null2String(properties[i].getValue());
            if (name.equals("xgr")) {
                xgr = value;
            } else if (name.equals("xdnxjssnx")) {
                xdnxjssnx = value;
            } else if (name.equals("jqlx")) {
                jqlx = value;
            }
        }

        List<Map<String, Object>> details = new ArrayList<>();
        //取明细数据
        DetailTable dt = requestinfo.getDetailTableInfo().getDetailTable()[0];
        // 当前明细表的所有数据,按行存储
        Row[] s = dt.getRow();
        for (int j = 0; j < s.length; j++) {
            Map<String, Object> map = new HashMap<>();
            // 指定行
            Row r = s[j];
            // 每行数据再按列存储
            Cell c[] = r.getCell();
            for (int k = 0; k < c.length; k++) {
                // 指定列
                Cell c1 = c[k];
                String name = c1.getName();// 明细字段名称
                String value = c1.getValue();// 明细字段的值
                map.put(name, value);
            }
            details.add(map);
        }

        if (!this.verify(jqlx, details, requestinfo)) {
            //必须返回false，否则流程会提交下去
            return FAILURE_AND_CONTINUE;
        }
        rst.setAutoCommit(false);
        try {

            for (Map<String, Object> map : details) {
                String sql = String.format("select t1.*, t2.minimumunit from kq_balanceOfLeave t1 INNER JOIN KQ_LeaveRules t2 on t2.id = t1.leaverulesid where t1.id = '%s'", map.get("yeid"));
                log.info("--------------------------------------------------------------------------------------" + sql);
                rs.execute(sql);  //余额表ID
                if (rs.next()) {
                    String belongyear = rs.getString("belongyear");
                    String baseamount = rs.getString("baseamount");
                    String usedamount = rs.getString("usedamount");
                    String extraamount = rs.getString("extraamount");
                    String baseamount2 = rs.getString("baseamount2");
                    String usedamount2 = rs.getString("usedamount2");
                    String extraamount2 = rs.getString("extraamount2");
                    String minimumunit = rs.getString("minimumunit");

                    String sql1 = "update kq_balanceOfLeave set expirationdate = ? where id = ?";
                    String sql2 = "INSERT INTO kq_UsageHistory(leaverulesid,relatedid,operator,operatedate,operatetime,operatetype,belongyear,oldminimumunit," +
                            "newminimumunit,insertorupdate,oldbaseamount,oldextraamount,oldusedamount,oldbaseamount2,oldextraamount2,oldusedamount2," +
                            "newbaseamount,newextraamount,newusedamount,newbaseamount2,newextraamount2,newusedamount2,wfrequestid,balanceofleaveid,workflowid)" +
                            "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    log.info("--------------------------------------------------------------------------------------" + sql1);
                    log.info("--------------------------------------------------------------------------------------" + sql2);

                    rst.executeUpdate(sql1, map.get("xyxq"), map.get("yeid"));
                    rst.executeUpdate(sql2, jqlx    , map.get("xm"), xgr, DateUtil.date().toDateStr(), DateUtil.date().toTimeStr()
                            , "6", belongyear, minimumunit, minimumunit, "update", baseamount, extraamount, usedamount, baseamount2, extraamount2, usedamount2
                            , baseamount, extraamount, usedamount, baseamount2, extraamount2, usedamount2, requestid, null, workflowid);
                }
            }
            rst.commit(); // 提交事务
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback(); // 事务回滚
            requestinfo.getRequestManager().setMessageid(System.currentTimeMillis() + "");
            requestinfo.getRequestManager().setMessagecontent("数据更新失败: 请联系管理员检查");
            return FAILURE_AND_CONTINUE;
        }

        return SUCCESS;
    }

    private boolean verify( String rulesId, List<Map<String, Object>> details, RequestInfo requestinfo){
        //数据源获取
        RecordSet rs = new RecordSet();
        for (Map<String, Object> map : details){
            map.get("xm");  //被修改人ID
            map.get("ssnf"); //假期所属年份
            map.get("syjqye"); //剩余假期余额
            map.get("dqyxq"); //当前有效期
            map.get("xyxq"); //新有效期
            map.get("yeid"); //余额表ID


            boolean isValid = com.fapiao.neon.util.DateUtil.isDate(map.get("xyxq")+"");
            if (!isValid){
                requestinfo.getRequestManager().setMessageid(System.currentTimeMillis() + "");
                requestinfo.getRequestManager().setMessagecontent("数据验证失败: " + map.get("xm") + " 该用户数据不正确，请检查！");
                return false;
            }
            String sql ="select * from kq_balanceOfLeave where id = " + map.get("yeid");
            rs.execute(sql);
            if (rs.next()){
                String  leaverulesid = rs.getString("leaverulesid");
                String  resourceid = rs.getString("resourceid");
                String  belongyear = rs.getString("belongyear");
                if (!resourceid.equals(map.get("xm")) || !rulesId.equals(leaverulesid) || !belongyear.equals(map.get("ssnf"))){
                    requestinfo.getRequestManager().setMessageid(System.currentTimeMillis() + "");
                    requestinfo.getRequestManager().setMessagecontent("数据验证失败: " + map.get("xm") + " 该用户数据不正确2，请检查！");
                    return false;
                }
            }else {
                requestinfo.getRequestManager().setMessageid(System.currentTimeMillis() + "");
                requestinfo.getRequestManager().setMessagecontent("数据验证失败: " + map.get("yeid") + " 找不到该用户，请检查！");
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.date().toDateStr());
        System.out.println(DateUtil.date().toTimeStr());

    }
}
